package com.umeng.commm.ui.fragments;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import com.umeng.comm.core.beans.BaseBean;
import com.umeng.comm.core.beans.Topic;
import com.umeng.comm.core.constants.Constants;
import com.umeng.comm.core.utils.Log;
import com.umeng.comm.core.utils.ResFinder;
import com.umeng.commm.ui.adapters.viewholders.SearchTopicAdapter;
import com.umeng.commm.ui.mvpview.MvpRecyclerView;
import com.umeng.commm.ui.presenter.BaseFragmentPresenter;
import com.umeng.commm.ui.presenter.impl.TopicSearchPresenter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangfei on 15/12/8.
 */
public class SearchTopicFragment<T extends List<BaseBean>, VH extends RecyclerView.ViewHolder> extends BaseFragment<List<Topic>, TopicSearchPresenter> implements MvpRecyclerView {
    private ArrayList<Topic> mTopicList = new ArrayList<Topic>();
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter<SearchTopicAdapter.TopicViewHolder> mTopicAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private EditText mSearchEditText;
    private BaseFragmentPresenter mPresenter;
    private android.os.Handler mSearchHandler;
    private Runnable mSearchRunnable;
    private ImageView mBackButton;
    private ProgressDialog mProgressDialog;
    private String mTextBefore="";

    @Override
    protected int getFragmentLayout() {
        return ResFinder.getLayout("umeng_search_topic");
    }

    @Override
    protected void initWidgets() {
        mBackButton = mViewFinder.findViewById(ResFinder.getId("umeng_comm_back"));
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setMessage("加载中...");
                mBackButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getActivity().finish();
                    }
                });
        mSearchHandler = new android.os.Handler();
        mSearchEditText = mViewFinder.findViewById(ResFinder.getId("umeng_comm_topic_edittext"));
        mRecyclerView = mViewFinder.findViewById(ResFinder.getId("umeng_comm_relative_user_recyclerView"));

        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                int postition = linearLayoutManager.findLastCompletelyVisibleItemPosition();
                if (postition == mTopicList.size() - 1) {
                    ((TopicSearchPresenter) mPresenter).fetchNextPageData();
                }
            }
        });
        mTopicAdapter = new SearchTopicAdapter(mTopicList,getActivity());
        mRecyclerView.setAdapter(mTopicAdapter);
        mSearchEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && !mSearchEditText.getText().toString().equals(mTextBefore)) {
                    ((TopicSearchPresenter) mPresenter).executeSearch(mSearchEditText.getText()
                            .toString().trim());
                }
                return false;
            }
        });
        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    if (!mTextBefore.equals(s.toString())) {
                        mSearchRunnable = new Runnable() {
                            @Override
                            public void run() {
                                ((TopicSearchPresenter) mPresenter).executeSearch(s.toString().trim());
                            }
                        };
                        mSearchHandler.postDelayed(mSearchRunnable, 300);
                    }
                    mTextBefore = s.toString();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        showSoftKeyboard(mSearchEditText);
        IntentFilter intentFilter = new IntentFilter(Constants.TOPIC_ACTION);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent!=null){
                    Topic topic = intent.getParcelableExtra("topic");
                    int index = mTopicList.indexOf(topic);
                    mTopicList.remove(index);
                    mTopicList.add(index,topic);
                    mTopicAdapter.notifyDataSetChanged();
                }
            }
        },intentFilter);
    }

    @Override
    protected TopicSearchPresenter createPresenters() {
        mPresenter = new TopicSearchPresenter(this,  mTopicList);
        return (TopicSearchPresenter) mPresenter;
    }


    @Override
    public void onDataSetChanged() {
        mTopicAdapter.notifyDataSetChanged();
    }

    private void showSoftKeyboard(View view) {
        if (view.requestFocus()) {
            InputMethodManager imm = (InputMethodManager)
                    getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    @Override
    public void showProgressFooter() {
        mProgressDialog.show();
    }

    @Override
    public void hideProgressFooter() {
        if(mProgressDialog.isShowing()){
            mProgressDialog.hide();
        }
    }


    @Override
    public void onRefreshStart() {

    }

    @Override
    public void onRefreshEnd() {

    }
}
